package com.lichuandi.controller;

import com.google.gson.JsonParser;
import com.lichuandi.crawler.ChaoJiYing;
import net.sourceforge.tess4j.Tesseract;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.web.bind.annotation.GetMapping;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class MainController {
    public static void main(String[] args) {
        String pageContent = getPageContent();
        System.out.println(pageContent);
    }
    public static String getPageContent() {
        try {
            String url = "https://me.sichuanair.com/login.shtml"; // 要爬取的网页URL
            String url2 = "https://me.sichuanair.com/api/v1/security/loginSC"; // 要爬取的网页URL
            //   Connection connect = Jsoup.connect(url2);
//header("Content-Type", "application/javascript; charset=utf-8")
            //  Document document = Jsoup.connect(url2).ignoreContentType(true).get();
// Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36
            Connection connection = Jsoup.connect(url).
                    header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:52.0) Gecko/20100101 Firefox/52.0");
            connection.method(Connection.Method.GET);
            connection.followRedirects(false);
            // 获取响应
            Connection.Response response = connection.execute();
            Map<String, String> cookies = response.cookies();
            System.out.println(cookies);
            /*
            304Response login = connect.ignoreContentType(true).followRedirects(true)
                    .method(Connection.Method.POST).data(datas).cookies(response.cookies()).execute();*/
            Document document = Jsoup.parse(response.body());
            //  System.out.println(document);
            //  Element imgElement = document.selectFirst("img[src$=.jpg]");
            Elements select = document.select("#img_vcode");
            // https://me.sichuanair.com/verifyScCode
            String src = select.attr("src");
            String logs = "https://me.sichuanair.com/verifyScCode?t_" + System.currentTimeMillis();
            System.out.println(logs);
            // URL url1 = new URL("https://me.sichuanair.com/verifyScCode?t_" + new Date().getTime());
            URL url1 = new URL("https://me.sichuanair.com/verifyScCode");

            getStream(url1);
            // 使用OCR识别
            Tesseract tesseract = new Tesseract();
            tesseract.setDatapath("F:\\vcode\\OCR");
            //String s1 = tesseract.doOCR(new File("F:\\vcode\\OCR"));


            /*String s1 = ChaoJiYing.PostPic("amfreak", "qwe12345", "914695", "3004", "0", "F:\\vcode\\myVCode.jpg");
            //String s2 = ChaoJiYing.PostPic_base64("amfreak", "qwe12345", "914695", "3004", "0", "F:\\vcode\\myVCode.jpg");
            JsonParser jp = new JsonParser();
            JsonObject asJsonObject = jp.parse(s1).getAsJsonObject();
            String pic_str = asJsonObject.get("pic_str").getAsString();
            System.out.println(s1);*/

            // ChaoJiYing.PostPic()

            Elements elements = document.select("#mform");

            // 获取cookie和表单
            Map<String, String> datas = new HashMap<>();


            for (Element e : elements.get(0).getAllElements()) {
                // 设置用户
                if (e.attr("name").equals("username")) {
                    e.attr("value", "o18750");
                }
                if (e.attr("name").equals("userPassword")) {
                    e.attr("value", "NUvjWmbmzFZIS1hOd0Uo0rXjJcF/W+94PTT1DBLyAV2dIALLMMktJjjY6y4AQD+QXbkxNgASvSjEMC2ldO+14g==");
                }
                if (e.attr("name").equals("vCode")) {
                    e.attr("value", "AAAA");

                }
                // 排除空值表单属性
                if (e.attr("name").length() > 0) {
                    datas.put(e.attr("name"), e.attr("value"));
                }
            }


            //  Element body = document.body();

            String pageContent = document.html();

            System.out.println(datas);

            // 第二次请求 POST的方式提交表单数据以及cookie
            Connection connect = Jsoup.connect("https://me.sichuanair.com/api/v1/security/loginSC");
            connect.header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:52.0) Gecko/20100101 Firefox/52.0");
            // 设置cookie和post上面的map数据
            Connection.Response login = connect.ignoreContentType(true).followRedirects(true)
                    .method(Connection.Method.POST).data(datas).cookies(response.cookies()).execute();
            System.out.println(login.body());
            // 登录成功之后的cookie信息，保存在本地，以后登录时候，只需一次登录即可
            Map<String, String> map = login.cookies();
            for (String s : map.keySet()) {
                System.out.println(s + ":" + map.get(s));
            }
            Document document2 = Jsoup.parse(login.body());
            String html = document2.html();
            //登录之后的操作
            // 第一次登录验证码错之后，第二次刷新验证码和cookie
            URL vCode = new URL("https://me.sichuanair.com/verifyScCode?t_" + System.currentTimeMillis());
            System.out.println(vCode);

            getStream(vCode);
            String postPic = ChaoJiYing.PostPic("amfreak", "qwe12345", "914695", "3004", "0", "F:\\vcode\\myVCode.jpg");
            System.out.println("刷新验证码:" + postPic);
            String pic_str2 = JsonParser.parseString(postPic).getAsJsonObject().get("pic_str").getAsString();
            System.out.println(pic_str2);
            datas.put("vCode", pic_str2);
            System.out.println(datas);
            // 再次提交表单
            Connection reLogin = Jsoup.connect("https://me.sichuanair.com/api/v1/security/loginSC");
            reLogin.header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:52.0) Gecko/20100101 Firefox/52.0");
            // 设置cookie和post上面的map数据
            Connection.Response execute = reLogin.ignoreContentType(true).followRedirects(false)
                    .method(Connection.Method.POST).data(datas).cookies(login.cookies()).execute();

            Document parse = Jsoup.parse(execute.body());
            Map<String, String> cookies1 = execute.cookies();
            for (String s : cookies1.keySet()) {
                System.out.println(s + ":" + cookies1.get(s));
            }
            // System.out.println(cookies1);
            // return document.html();
            return parse.html();

        } catch (Exception e) {
            return "Error: " + e.getMessage();
        }
    }

    private static void getStream(URL url1) throws IOException {
        InputStream inputStream = url1.openStream();
        FileOutputStream outputStream = new FileOutputStream("F:\\vcode\\myVCode.jpg");
        byte[] bytes = new byte[1024];
        int bytesRead;
        while ((bytesRead = inputStream.read(bytes)) != -1) {
            outputStream.write(bytes, 0, bytesRead);
        }
        outputStream.close();
        inputStream.close();
        // return outputStream;
    }
}
